package com.swordget.service.impl;

import com.swordget.dao.impl.BaseDataMappingDaoImpl;
import com.swordget.entity.po.BaseDataMappingPo;
import com.swordget.entity.vo.BaseDataMappingTypeVo;
import com.swordget.entity.vo.BaseDataMappingVo;
import com.swordget.exception.ResolveException;
import com.swordget.exception.VerifyFailException;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedInputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Author: David
 * @Date: Created in 9:33 2021/5/8
 * @Description: 基础数据映射 Service
 * @Modified By:
 * @Version:
 */

@Service
public class BaseDataMappingService {

    @Autowired
    private BaseDataMappingDaoImpl baseDataMappingDao;

    public List<BaseDataMappingTypeVo> getDataType() {

        Map<Integer, List<String>> map = baseDataMappingDao.groupByType();
        List<BaseDataMappingTypeVo> dataList = new ArrayList<>(map.size());
        for (Map.Entry<Integer, List<String>> entry : map.entrySet()) {
            List<String> list = entry.getValue();
            BaseDataMappingTypeVo type = new BaseDataMappingTypeVo(list.get(0), list.get(1));
            dataList.add(type);
        }
        return dataList;
    }

    public List<BaseDataMappingVo> getData(String type) {
        Map<Integer, List<String>> map = baseDataMappingDao.findAllByType(type);
        List<BaseDataMappingVo> dataList = new ArrayList<>(map.size());
        for (Map.Entry<Integer, List<String>> entry : map.entrySet()) {
            List<String> list = entry.getValue();
            BaseDataMappingVo data = new BaseDataMappingVo(list.get(0), list.get(1));
            dataList.add(data);
        }
        return dataList;
    }

    public boolean importData(String typeName, MultipartFile file) {
        //先查一下是否有此类基础编码
        int count = baseDataMappingDao.countByType(typeName);
        if (count > 0) {
            throw new VerifyFailException("已存在此类型，基础编码!!!");
        }
        List<BaseDataMappingPo> mappingPos = new ArrayList<>();
        //解析文件导入到数据库
        try (Workbook workbook = new XSSFWorkbook(new BufferedInputStream(file.getInputStream()));) {
            Sheet sheet = workbook.getSheetAt(0);
            int lastRowNum = sheet.getLastRowNum();
            for (int i = 1; i <= lastRowNum; i++) {
                Row row = sheet.getRow(i);
                Cell cell1 = row.getCell(0);
                Cell cell2 = row.getCell(1);
                if (cell1 != null && cell2 != null) {
                    BaseDataMappingPo mappingPo = new BaseDataMappingPo(typeName, numberCoverString(cell1), numberCoverString(cell2));
                    mappingPos.add(mappingPo);
                }
            }
        } catch (Exception e) {
            throw new ResolveException("无法解析文件", e);
        }
        return baseDataMappingDao.save(mappingPos);
    }

    private String numberCoverString(Cell cell) {
        if (cell != null) {
            CellType cellType = cell.getCellType();
            if (cellType.getCode() == 0 || cellType.getCode() == 2) {
                double cellValue = cell.getNumericCellValue();
                return String.valueOf(cellValue);
            } if (cellType.getCode() == 4) {
                boolean cellValue = cell.getBooleanCellValue();
                return String.valueOf(cellValue);
            }
            return cell.getStringCellValue();
        }
        throw new NullPointerException();
    }

    public List<BaseDataMappingVo> baseUrlList() throws UnsupportedEncodingException {
        Map<Integer, List<String>> map = baseDataMappingDao.groupByType();
        List<BaseDataMappingVo> dataList = new ArrayList<>(map.size());
        for (Map.Entry<Integer, List<String>> entry : map.entrySet()) {
            List<String> list = entry.getValue();
            String type = list.get(0);
            String url = String.format("/baseData/data/%s", URLEncoder.encode(type, "UTF-8"));
            dataList.add(new BaseDataMappingVo(url, type));
        }
        return dataList;
    }
}
